package cn.tedu.boot02_1.controller;

import cn.tedu.boot02_1.entity.Product_1;
import cn.tedu.boot02_1.utils.DBUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@RestController
public class Product_1Controller {
    @RequestMapping("/insert")
    public String insert(Product_1 product_1) {
        System.out.println("product_1 = " + product_1);
        try(
            Connection connection = DBUtil.getConnection();
        ) {
            /*
            INSERT INTO product_1 VALUES(NULL, ?, ?, ?)
            */
            String sql = "INSERT INTO product_1 VALUES(NULL, ?, ?, ?) ";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, product_1.getTitle());
            ps.setDouble(2, product_1.getPrice());
            ps.setInt(3, product_1.getNum());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "添加完成!";
    }

    @RequestMapping("/select")
    public String select() {
        ArrayList<Product_1> list = new ArrayList<>();
        try(Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM product_1";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                Product_1 p1 = new Product_1();
                p1.setId(rs.getInt("id"));
                p1.setTitle(rs.getString("title"));
                p1.setPrice(rs.getDouble("price"));
                p1.setNum(rs.getInt("num"));
                list.add(p1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list.toString();
    }

}
